<?php
/**
 * Create By: PhpStorm
 * User: yuanxuncheng
 * File: CreateOrder.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\order;

use app\api\model\dao\Cart;
use app\api\model\dao\Goods;
use app\api\model\dao\GoodsSpec;
use app\api\model\dao\OrderInfo;
use app\api\model\dao\OrderGoods;
use app\api\model\dao\UserAddress;
use app\library\Error;
use app\library\PageBase;
use think\Validate;
use think\Cache;
use think\Log;
use app\library\Flag;

class CreateOrder extends PageBase
{
    private $objOrderInfo;
    private $objOrderGoods;
    private $objUserAddress;
    private $objGoods;
    private $objGoodsSpec;
    private $objCart;

    public function __construct()
    {
        parent::__construct();
        $this->objOrderInfo = new OrderInfo();
        $this->objOrderGoods = new OrderGoods();
        $this->objUserAddress = new UserAddress();
        $this->objGoods = new Goods();
        $this->objGoodsSpec = new GoodsSpec();
        $this->objCart = new Cart();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'cart_data' => 'require',
            'address_id' => 'require',
            'remark' => 'require',
            'pay_id' => 'require',
        ];
        $msg = [
            'cart_data.require' => '购物车商品信息必填',
            'address_id.require' => '地址ID必填',
            'remark.require' => '订单备注必填',
            'pay_id.require' => '支付方式必填',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }

        // TODO:业务逻辑
        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM, $ret);
        }

        $user_id = $this->user_id;
        $cart_data = $param['cart_data'];
        $cart_data = json_decode($cart_data, true);

        if (empty($cart_data)) {
            return $this->getRes(Error::ERR_SYS);
        }

        $address_id = $param['address_id'];
        // 获取用户地址
        $address = $this->objUserAddress->getAddressById($address_id);
        if (empty($address)) {
            return $this->getRes(Error::ERR_SYS);
        }

        $this->objOrderInfo->db(true)->startTrans();

        $goods_amount_sum = 0;
        $order_amount_sum = 0;

        // 验证商购物车品信息
        foreach ($cart_data as $data) {
            $goods_id = $data['goods_id'];
            $goods_number_selected = $data['goods_number'];
            $goods_spec_id = $data['goods_spec_id'];
            // 添加订单商品关联信息
            $goods = $this->objGoods->getGoods($goods_id);
            $goods_spec = $this->objGoodsSpec->getGoodsSpecByid($goods_spec_id);
            $goods_number = $goods[0]['goods_number'];
            $goods_spec_number = $goods_spec[0]['spec_goods_number'];
            $spec_price = $goods_spec[0]['spec_price'];
            if ($goods_number_selected > $goods_number
                || $goods_number_selected > $goods_spec_number
            ) {
                return $this->getRes(Error::ERROR_CART_GOODS_NUMBER_ERROR);
            }
            $goods_amount_sum += $spec_price * $goods_number_selected;
        }

        // 计算其它

        // 订单信息
        $param['best_time'] = time();
        $param['goods_amount'] = $goods_amount_sum;
        $order_amount_sum = $goods_amount_sum;
        $param['order_amount'] = $order_amount_sum;
        $param['discount'] = '' . round($order_amount_sum / $goods_amount_sum, 2) * 10;

        $order_id = $this->objOrderInfo->generalOrderid();
        $order['order_id'] = $order_id;
        $order['user_id'] = $user_id;
        $order['user_name'] = $this->user_name;
        $order['order_status'] = Flag::ORDER_STATUS_NOT_PAY;
        $order['shipping_status'] = Flag::SHIPPING_STATUS_NOT_SENDING;
        $order['pay_status'] = Flag::PAY_STATUS_NOT;
        $order['consignee'] = $address['consignee'];
        $order['country'] = $address['country'];
        $order['province'] = $address['province'];
        $order['city'] = $address['city'];
        $order['district'] = $address['district'];
        $order['address'] = $address['address'];
        $order['zipcode'] = $address['zipcode'];
        $order['tel'] = $address['tel'];
        $order['mobile'] = $address['mobile'];
        $order['best_time'] = $param['best_time'];
        $order['goods_amount'] = $param['goods_amount'];
        $order['order_amount'] = $param['order_amount'];
        $order['discount'] = $param['discount'];
        $order['pay_id'] = $param['pay_id'];
        $order['add_time'] = time();
        $ret = $this->objOrderInfo->addOrder($order);
        // 计算订单金额

        $saves = array();
        foreach ($cart_data as $data) {
            // 订单商品信息
            $goods_id = $data['goods_id'];
            $goods_number = $data['goods_number'];
            $goods_spec_id = $data['goods_spec_id'];
            // 添加订单商品关联信息
            $goods = $this->objGoods->getGoods($goods_id);
            $goods_spec = $this->objGoodsSpec->getGoodsSpecByid($goods_spec_id);

            $save = array();
            $save['order_id'] = $order_id;
            $save['goods_id'] = $goods_id;
            $save['goods_name'] = $goods[0]['goods_name'];
            $save['goods_number'] = $goods_number;
            $save['market_price'] = $goods[0]['market_price'];
            $save['shop_price'] = $goods[0]['shop_price'];
            $save['goods_spec_id'] = $goods_spec[0]['goods_spec_id'];
            $save['goods_spec_name'] = $goods_spec[0]['spec_name'];
            $save['is_hot'] = $goods[0]['is_hot'];
            $save['is_new'] = $goods[0]['is_new'];
            $save['is_promote'] = $goods[0]['is_promote'];
            $save['is_free_shipping'] = $goods[0]['is_free_shipping'];
            $save['is_special_packing'] = $goods[0]['is_special_packing'];
            $saves[] = $save;
            $this->objCart->deleteCart($user_id, $goods_id, $goods_spec_id);
        }
        $ret = $this->objOrderGoods->addOrderGoods($saves);

        if ($order_id && $ret) {
            $this->objOrderInfo->db(true)->commit();
        } else {
            $this->objOrderInfo->db(true)->rollback();
            Log::alert(__METHOD__ . ' ret: ' . json_encode($param));
            return $this->getRes(Error::ERR_SYS);
        }
        $this->data = array(
            "order_id" => $order_id,
        );
        return $this->getRes();
    }
}
